package org.needcoke.hs.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@UtilityClass
public class ClassUtil {

    private Map<String, Class<?>> clzMap = new HashMap<>();

    private Map<String, Object> instanceMap = new HashMap<>();

    public Class<?> forName(String name) {
        if (clzMap.containsKey(name)) {
            return clzMap.get(name);
        } else {
            try {
                Class<?> clz = Class.forName(name);
                clzMap.put(name, clz);
                return clz;
            } catch (ClassNotFoundException e) {
                log.error("类路径下没有找到类 {}", name);
                throw new RuntimeException("类路径下没有找到该类 , " + name);
            }
        }
    }

    public Object instance(Class<?> clz) {
        if (instanceMap.containsKey(clz.getTypeName())) {
            return instanceMap.get(clz.getTypeName());
        }
        Constructor<?> constructor = null;
        try {
            constructor = clz.getConstructor(null);
        } catch (NoSuchMethodException e) {
            log.error("{} 没有无参构造函数 !", clz.getTypeName());
            throw new RuntimeException(clz.getTypeName() + " 没有无参构造函数 !");
        }
        try {
            Object instance = constructor.newInstance(null);
            instanceMap.put(clz.getTypeName(), instance);
            return instance;
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            log.error("{} 实例化失败 !", clz.getTypeName());
            throw new RuntimeException(e);
        }
    }
}
